package com.example.agriapp;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.example.agriapp.model.bean.Product;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class BuyerHomePresenter implements BuyerHomeContract.Presenter {
    private static final String TAG = "BuyerHomePresenter";
    private BuyerHomeContract.View view;
    private ContentResolver contentResolver;
    private Context context;
    private final CompositeDisposable disposables = new CompositeDisposable();

    public BuyerHomePresenter(BuyerHomeContract.View view, Context context) {
        this.view = view;
        this.context = context;
        this.contentResolver = context.getContentResolver();
    }

    @Override
    public void loadProducts() {
        view.showLoading();
        List<Product> products = getAllProducts();
        Log.e(TAG, "loadProducts: "+products.size() );
        if (products.isEmpty()) {
            view.showEmptyView();
        } else {
            view.showProducts(products);
        }
        view.hideLoading();
    }

    @Override
    public void loadProductsByCategory(String category) {
        view.showLoading();
        List<Product> products = getProductsByCategory(category);
        if (products.isEmpty()) {
            view.showEmptyView();
        } else {
            view.showProducts(products);
        }
        view.hideLoading();
    }

    @Override
    public void searchProducts(String query) {
        disposables.add(Observable.fromCallable(() -> searchProductsByQuery(query))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(products -> {
                    if (products.isEmpty()) {
                        view.showEmptyView();
                    } else {
                        view.showProducts(products);
                    }
                    view.hideLoading();
                }, throwable -> {
                    Log.e(TAG, "Search error", throwable);
                    view.hideLoading();
                    view.showError("搜索失败");
                }));

    }

    private List<Product> getAllProducts() {
        List<Product> products = new ArrayList<>();
        Cursor cursor = contentResolver.query(
                ProductContract.ProductEntry.CONTENT_URI,
                null,
                null,
                null,
                null
        );

        if (cursor != null) {
            try {
                while (cursor.moveToNext()) {
                    Product product = new Product();
                    product.setId(cursor.getInt(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_ID)));
                    product.setTitle(cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_TITLE)));
                    product.setPrice(cursor.getDouble(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRICE)));
                    product.setQuantity(cursor.getInt(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_QUANTITY)));
                    product.setCategory(cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_CATEGORY)));
                    product.setImage(cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_IMAGE)));

                    products.add(product);
                }
            } finally {
                cursor.close();
            }
        }
        return products;
    }

    private List<Product> getProductsByCategory(String category) {
        List<Product> products = new ArrayList<>();
        Cursor cursor = contentResolver.query(
                ProductContract.ProductEntry.CONTENT_URI,
                null,
                ProductContract.ProductEntry.COLUMN_CATEGORY + " = ?",
                new String[]{category},
                null
        );

        if (cursor != null) {
            try {
                while (cursor.moveToNext()) {
                    Product product = new Product();
                    product.setId(cursor.getInt(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_ID)));
                    product.setTitle(cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_TITLE)));
                    product.setPrice(cursor.getDouble(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRICE)));
                    product.setQuantity(cursor.getInt(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_QUANTITY)));
                    product.setCategory(cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_CATEGORY)));
                    product.setImage(cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_IMAGE)));

                    products.add(product);
                }
            } finally {
                cursor.close();
            }
        }
        return products;
    }

    private List<Product> searchProductsByQuery(String query) {
        List<Product> products = new ArrayList<>();
        Cursor cursor = contentResolver.query(
                ProductContract.ProductEntry.CONTENT_URI,
                null,
                ProductContract.ProductEntry.COLUMN_TITLE + " LIKE ? OR " + 
                ProductContract.ProductEntry.COLUMN_CATEGORY + " LIKE ?",
                new String[]{"%" + query + "%", "%" + query + "%"},
                null
        );

        if (cursor != null) {
            try {
                while (cursor.moveToNext()) {
                    Product product = new Product();
                    product.setId(cursor.getInt(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_ID)));
                    product.setTitle(cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_TITLE)));
                    product.setPrice(cursor.getDouble(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_PRICE)));
                    product.setQuantity(cursor.getInt(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_QUANTITY)));
                    product.setCategory(cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_CATEGORY)));
                    product.setImage(cursor.getString(cursor.getColumnIndex(ProductContract.ProductEntry.COLUMN_IMAGE)));

                    products.add(product);
                }
            } finally {
                cursor.close();
            }
        }
        return products;
    }

    @Override
    public void onDestroy() {
        view = null;
        contentResolver = null;
    }
}